<template>
  <qx-table :dbRowClick="rowDblClick" :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <qx-form v-model="searchForm" :option="tableOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-slot:menuLeft>
      <q-btn outline text-color="primary" @click="handleSync">
        {{ $t('Misc.SynchronousHeadquarters') }}
      </q-btn>
    </template>
    <template v-slot:menuLeftR>
      <q-icon color="warning" name="mdi-map-marker-question cursor-pointer cursor-hover" size="1.5rem">
        <q-tooltip class="q-pa-md" v-bind="$tooltipAttr">{{ $t('Misc.DblClickCardTips') }}</q-tooltip>
      </q-icon>
    </template>
    <template v-slot:menu="{ row }">
      <q-btn :disable="!row.pageJson" class="col" color="primary" no-wrap outline unelevated
             @click="handleExtParams(row)">
        {{ $t('Misc.EnhanceExtParams') }}
      </q-btn>
      <q-btn v-if="row.isEnable === '0'" class="col" color="primary" no-wrap outline unelevated
             @click="handleIsEnable(row, '1')">
        {{ $t('Enable') }}
      </q-btn>
      <q-btn v-if="row.isEnable === '1'" class="col" color="primary" no-wrap outline unelevated
             @click="handleIsEnable(row, '0')">
        {{ $t('Disable') }}
      </q-btn>
    </template>
  </qx-table>
  <q-modal v-model="modalVisible" :header="$t('Misc.EnhanceExtParams')" :width="500" btnAlign="center" position="right"
           @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="formOption">
      <template v-slot:extParams>
        <div class="warning-tips text-weight-medium row items-center no-wrap">
          <q-icon class="map-warning-tips-icon" name="mdi-information-variant" size="1.25rem"></q-icon>
          <div>{{ $t('Misc.ExtParams') }}</div>
        </div>
      </template>
    </qx-form>
  </q-modal>
  <q-modal v-model="infoVisible" :header="`${$t('Misc.SpecifyDetails')}`" :menuBtn="false" :persistent="false"
           width="620">
    <QInfo :columns="tableOption.column || []" :rowInfo="formInfo" cols="2" headerWidth="100"></QInfo>
    <template v-if="extColumns.length">
      <div class="warning-tips text-weight-medium row items-center no-wrap q-my-sm">
        <q-icon class="map-warning-tips-icon" name="mdi-information-variant" size="1.25rem"></q-icon>
        <div>{{ $t('Misc.ExtParams') }}</div>
      </div>
      <QInfo :columns="extColumns || []" :rowInfo="rowInfo" cols="2" headerWidth="100"></QInfo>
    </template>
  </q-modal>
</template>
<script setup>
import { i18n, toI18nName } from 'boot/i18n.js'
import { postAPI, putAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { enableOrDisable, yesOrNo } from 'src/enum/index.js'
import { computed, onMounted, ref } from 'vue'
import { createDialog, isJSON } from 'src/utils/utils.js'

const rowInfo = ref({})
const formInfo = ref({})
const FormRef = ref(null)
const AGVBrands = ref([])
const searchForm = ref({})
const extColumns = ref([])
const infoVisible = ref(false)
const modalVisible = ref(false)
const remoteData = ref({ dicUrl: '/yfagv/api/sdaiRcsProtocol/list' })
getRemoteData('agv_brand', '/yfagv/api/agvCfgBrand/list').then(data => (AGVBrands.value = data))
const PlugInTypes = computed(() => {
  return [{
    label: `${i18n.t('RCSCore.PlugInTypeTip1')}`, value: '10'
  }, {
    label: `${i18n.t('RCSCore.PlugInTypeTip4')}`, value: '11'
  }, {
    label: `${i18n.t('RCSCore.PlugInTypeTip2')}`, value: '20'
  }, {
    label: `${i18n.t('RCSCore.PlugInTypeTip3')}`, value: '30'
  }, {
    label: `${i18n.t('RCSCore.PlugInTypeTip5')}`, value: '40'
  }]
})
const tableOption = computed(() => {
  return {
    grid: true, span: 22, export: true, labelWidth: 100, searchSpan: 4, headerWidth: 60,
    searchLabelWidth: 60,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      minWidth: 100, props: { label: `${toI18nName('agvBrandNameZhCn')}`, value: 'agvBrandCode' },
      readonly: true
    }, {
      label: `${i18n.t('RCSCore.PlugInType')}`, field: 'jarType', type: 'select', readonly: true,
      options: PlugInTypes.value, minWidth: 100
    }, {
      label: `${i18n.t('RCSCore.PlugInURL')}`, field: 'jarUrl', readonly: true, minWidth: 70, search: false,
      display: false
    }, {
      label: `${i18n.t('RCSCore.PlugInVersion')}`, field: 'jarVersion', minWidth: 80, hide: true, search: false,
      display: false, topLeft: true
    }, {
      label: `${i18n.t('RCSCore.PlugInClassName')}`, field: 'jarClassName', readonly: true, minWidth: 70, hide: true,
      search: false
    }, {
      label: `${i18n.t('RCSCore.PlugInServiceName')}`, field: 'jarServerName', readonly: true, minWidth: 70, hide: true,
      search: false
    }, {
      label: `${i18n.t('Misc.InitMethodName')}`, field: 'initMethodName', readonly: true, minWidth: 70, hide: true,
      search: false
    }, {
      label: `${i18n.t('Misc.WebInterface')}`, field: 'isController', type: 'select', display: false,
      options: yesOrNo.value, useTag: true, minWidth: 80
    }, {
      label: `${i18n.t('IsEnable')}`, field: 'isEnable', type: 'radio', searchType: 'select', value: '1',
      options: enableOrDisable.value, useTag: true, topRight: true, display: false
    }, {
      label: `${i18n.t('Misc.SynchronousTime')}`, field: 'createdTime', display: false, minWidth: 80, search: false
    }, {
      label: `${i18n.t('Remarks')}`, field: 'remark', type: 'textarea', minWidth: 100, search: false, hide: true,
      display: false
    }]
  }
})
const formOption = computed(() => {
  return {
    span: 22, labelWidth: 110,
    column: [...tableOption.value.column, { field: 'extParams', labelWidth: 0, formslot: true, span: 24 },
      ...extColumns.value]
  }
})

const handleSync = () => {
  createDialog({ msg: `${i18n.t('Misc.SyncTip3')}` }, () => {
    postAPI('/yfagv/api/syncAgvCfg/syncSdaiRcsProtocol', {}, () => startSearch('clear'))
  })
}
const formatOption = column => {
  if (!column || !isJSON(column)) return []
  const parse = JSON.parse(column), list = parse instanceof Array ? parse : parse instanceof Object ? [parse] : []
  return list.map(el => {
    el.label = el[toI18nName('labelZhCn')] ?? el.label
    return el
  })
}
const rowDblClick = row => {
  const { handleExtraParam, pageJson, ...params } = row
  const form = formatOption(handleExtraParam)[0] || {}
  formInfo.value = { ...params }
  rowInfo.value = { ...form }
  extColumns.value = formatOption(pageJson)
  infoVisible.value = true
}
const handleExtParams = row => {
  const { handleExtraParam, pageJson, ...params } = row
  const form = formatOption(handleExtraParam)[0] || {}
  formInfo.value = { ...params, ...form }
  extColumns.value = formatOption(pageJson)
  modalVisible.value = true
}
const handleIsEnable = (row = {}, isEnable) => {
  const msg = isEnable === '1' ? `${i18n.t('EnableTips')}` : `${i18n.t('DisableTips')}`, idList = [row.id]
  createDialog({ msg }, () => {
    putAPI('/yfagv/api/sdaiRcsProtocol/enableOrDisable', { idList, isEnable }, () => startSearch('clear'))
  }, () => {})
}
const formatSearchForm = () => ({ ...searchForm.value })
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
  action === 'clear' && setRemoteData('rcs_plugin')
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
}
const submitForm = mDone => {
  FormRef.value.validate((form, done) => {
    const handleExtraParam = {}
    for (const item of extColumns.value) handleExtraParam[item.field] = form[item.field]
    form.handleExtraParam = JSON.stringify(handleExtraParam)
    postAPI('/yfagv/api/sdaiRcsProtocol/saveHandJson', form, () => {
      startSearch()
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
onMounted(startSearch)
</script>